package org.jeecg.modules.system.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.BalanceInfo;
import org.jeecg.modules.system.entity.DetailInfo;
import org.jeecg.modules.system.mapper.DetailInfoMapper;
import org.jeecg.modules.system.service.IDetailInfoService;
import org.jeecg.modules.system.vo.Ids;
import org.jeecg.modules.util.ExcelUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 明细表
 * @Author: jeecg-boot
 * @Date:   2025-04-25
 * @Version: V1.0
 */
@Service
@Slf4j
public class DetailInfoServiceImpl extends ServiceImpl<DetailInfoMapper, DetailInfo> implements IDetailInfoService {

    @Autowired
    DetailInfoMapper detailInfoMapper;

    @Override
    @Transactional
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                Sheet sheet = new Sheet(1, 1);
                ExcelUtil.ExcelListener excelListener = new ExcelUtil.ExcelListener();
                EasyExcelFactory.readBySax(file.getInputStream(), sheet, excelListener);
                List<Object> objects = excelListener.getDatas();
                log.info("文件行数:{}",objects.size());
                List<DetailInfo> detailInfos = new ArrayList<>();
                boolean on = true;
                Date date = new Date();
                String name = "";
                String rate = "";
                for (Object o : objects) {
                    List<String> list = (ArrayList) o;
                    if(StringUtils.isBlank(list.get(0))){
                        continue;
                    }
                    if(list.get(0).startsWith("科目：")) {
                        if (list.get(0).contains("进项税")) {
                            rate = list.get(0).split("进项税")[1].split(".-.-.-")[0];
                        }else {
                            rate = "空";
                        }
                        continue;
                    }
                    if(list.get(0).startsWith("辅助核算")) {
                        String[] split = list.get(0).split(":");
                        name = split[split.length-1].replaceAll(".-] .","").split(" ")[0];
                        on = true;
                        continue;
                    }
                    if(list.get(0).startsWith("操作人")) {
                        on = false;
                        continue;
                    }
                    if (on) {
                        if (list.size()>=16 && ("EMS".equals(list.get(4))||"应付帐款".equals(list.get(4)))) {
                            DetailInfo detailInfo = new DetailInfo();
                            detailInfo.setDetailName(name);
                            detailInfo.setSource(list.get(4));
                            detailInfo.setDebit(list.get(10));
                            detailInfo.setCreateTime(date);
                            detailInfo.setRate(rate);
                            detailInfo.setAbstracts(list.get(5));
                            detailInfo.setJournalName(list.get(7));
                            detailInfo.setBatchName(list.get(6));

                            detailInfos.add(detailInfo);
                        }
                    }
                }
                detailInfoMapper.deleteAll();
                this.saveBatch(detailInfos);
                List<Ids> sameIds = detailInfoMapper.findSameIds();
                List<String> collect = sameIds.stream().map(Ids::getId).collect(Collectors.toList());
                collect.addAll(sameIds.stream().map(Ids::getIdb).collect(Collectors.toList()));
                log.info("删除相抵项目...");
                detailInfoMapper.deleteBatchIds(collect);
                return Result.ok("文件导入成功!");
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }
}
